package timing.ukulele.third.msgChannel.action.send;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import timing.ukulele.third.exception.ThirdServiceException;
import timing.ukulele.third.msgChannel.param.SendMessageParam;
import timing.ukulele.third.persistent.msg.MessageTemplate;
import timing.ukulele.third.service.msg.MessageTemplateService;
import java.util.Objects;

/**
 * @author zh
 * @date 2021/11/22
 * @description 发送消息：前置参数校验
 */
@Slf4j
@Service
public class SendPreCheckAndProcessAction {

    @Autowired
    private MessageTemplateService messageTemplateService;

    public MessageTemplate process(SendMessageParam sendMessageParam) {

        Long messageTemplateId = sendMessageParam.getMessageTemplateId();

        // 没有传入消息模板Id
        if (Objects.isNull(messageTemplateId)) {
            throw new ThirdServiceException("没有传入消息模板Id");
        }
        // 查询模板数据
        MessageTemplate messageTemplate = messageTemplateService.getById(messageTemplateId);
        if(messageTemplate == null) {
            throw new ThirdServiceException("找不到模板或模板已被删除");
        }

        // 验证消息接受者
        String receiver = sendMessageParam.getReceiver();
        if(StrUtil.isBlank(receiver)) {
            throw new ThirdServiceException("接受者参数为空");
        }
        // 过滤 receiver 大于100的请求
        if (receiver.split(StrPool.COMMA).length > 100) {
            throw new ThirdServiceException("传入的接收者大于100个");
        }

        return messageTemplate;
    }

}
